package org.example.adservice.controller;

import lombok.RequiredArgsConstructor;
import org.example.adservice.service.AdService;
import org.example.adservice.common.Result;
import org.example.pojo.Ad;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 广告控制器
 */
@RestController
@RequestMapping("/api/ads")
@RequiredArgsConstructor
public class AdController {

    private final AdService adService;

    /**
     * 查询所有广告
     */
    @GetMapping
    public Result<List<Ad>> getAllAds() {
        List<Ad> ads = adService.getAllAds();
        return Result.success(ads);
    }

    /**
     * 根据ID查询广告详情
     */
    @GetMapping("/{id}")
    public Result<Ad> getAdById(@PathVariable Integer id) {
        Ad ad = adService.getAdById(id);
        if (ad == null) {
            return Result.error("广告不存在");
        }
        return Result.success(ad);
    }

    /**
     * 创建广告
     */
    @PostMapping
    public Result<Ad> createAd(@RequestBody Ad ad) {
        Ad createdAd = adService.createAd(ad);
        return Result.success(createdAd);
    }

    /**
     * 更新广告
     */
    @PutMapping("/{id}")
    public Result<Ad> updateAd(@PathVariable Integer id, @RequestBody Ad ad) {
        Ad updatedAd = adService.updateAd(id, ad);
        return Result.success(updatedAd);
    }

    /**
     * 删除广告
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteAd(@PathVariable Integer id) {
        boolean success = adService.deleteAd(id);
        if (success) {
            return Result.success("广告删除成功");
        } else {
            return Result.error("广告删除失败");
        }
    }
}